using MediatR;
using TerritoryGame.Application.Queries;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.QueryHandlers;

public class GetGameStateQueryHandler : IRequestHandler<GetGameStateQuery, GetGameStateResult>
{
    private readonly IGameRepository _gameRepository;
    
    public GetGameStateQueryHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }
    
    public async Task<GetGameStateResult> Handle(GetGameStateQuery request, CancellationToken cancellationToken)
    {
        try
        {
            var game = await _gameRepository.GetByIdAsync(request.GameId);
            if (game == null)
            {
                return new GetGameStateResult
                {
                    Success = false,
                    ErrorMessage = "游戏不存在"
                };
            }
            
            var remainingTime = 0;
            if (game.Room.StartTime.HasValue && game.Room.Status == Domain.Entities.GameStatus.Playing)
            {
                var elapsed = DateTime.UtcNow - game.Room.StartTime.Value;
                remainingTime = Math.Max(0, game.Room.GameDuration - (int)elapsed.TotalSeconds);
            }
            
                                     var playerStates = game.Room.Players.Select(player => new PlayerStateInfo
            {
                Id = player.Id,
                NickName = player.NickName,
                Color = player.Color.Value,
                Score = player.CurrentScore.Value,
                Area = game.Canvas.GetPlayerArea(player.Color), // 计算玩家面积
                IsOnline = true // TODO: 实现在线状态检测
            }).ToList();
            
            var canvasInfo = new CanvasInfo
            {
                Width = game.Canvas.Width,
                Height = game.Canvas.Height,
                Pixels = game.Canvas.Pixels.ToDictionary(
                    kvp => $"{kvp.Key.X},{kvp.Key.Y}",
                    kvp => kvp.Value.Value
                )
            };
            
            var gameState = new GameStateInfo
            {
                GameId = game.Id,
                RoomId = game.Room.Id,
                RoomName = game.Room.Name,
                Status = game.Room.Status.ToString(),
                StartTime = game.Room.StartTime,
                GameDuration = game.Room.GameDuration,
                RemainingTime = remainingTime,
                Players = playerStates,
                Canvas = canvasInfo
            };
            
            return new GetGameStateResult
            {
                Success = true,
                GameState = gameState
            };
        }
        catch (Exception ex)
        {
            return new GetGameStateResult
            {
                Success = false,
                ErrorMessage = $"获取游戏状态失败: {ex.Message}"
            };
        }
    }
}
